package com.zhenyi.jiahua.core.utils;

import com.cjw.model.DBMap;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.LogKit;
import com.jiahua.common.model.JhMessage;
import com.jiahua.common.model.JhStaff;
import com.zhenyi.websocket.core.ws.WSServer;

public class MessageUtils {

	public static void send(Long staffId, Long fromStaffId, String title, String content) {
		if (staffId == null) {
			LogKit.info("发送staff null");
			return;
		}
		// if (fromStaffId == null) {
		// LogKit.info("发送fromStaffId null");
		// return;
		// }
		if (staffId.equals(fromStaffId)) {
			LogKit.info("不能发送给自己");
			return;
		}
		JhStaff staff = JhStaff.dao.findById(staffId);
		JhMessage message = new JhMessage();
		message.setTitle(title);
		message.setContent(content);
		message.setStaffId(staffId);
		message.setFromStaffId(fromStaffId);
		if (!message.save()) {
			LogKit.warn("保存消息失败");
			return;
		}
		Integer messageCount = staff.getMessageCount();
		if (messageCount == null) {
			messageCount = 0;
		}
		staff.setMessageCount(messageCount + 1);
		if (!staff.update()) {
			LogKit.warn("新增消息失败");
			return;
		}
		DBMap map = new DBMap();
		map.put("title", title);
		map.put("content", content);
		map.put("code", 102);
		String json = JsonKit.toJson(map);
		WSServer.instance().sendByToken(staff.getToken(), json);
	}
}
